package com.tripcube.ai.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tripcube.ai.model.dto.AddFileDTO;
import com.tripcube.ai.model.entity.Document;
import com.tripcube.ai.service.DocumentService;
import com.tripcube.common.core.web.controller.BaseController;
import com.tripcube.common.core.web.domain.AjaxResult;
import com.tripcube.common.core.web.page.TableDataInfo;
import com.tripcube.common.log.annotation.Log;
import com.tripcube.common.log.enums.BusinessType;
import com.tripcube.common.security.annotation.RequiresPermissions;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;


/**
 * 文档管理控制器
 *
 * @author alander
 */
@Tag(name = "文档管理", description = "知识库文档管理相关接口")
@RestController
@RequestMapping("/ai/document")
@RequiredArgsConstructor
@Slf4j
public class DocumentController extends BaseController {

    private final DocumentService documentService;

    /**
     * 查询文档列表
     */
    @Operation(summary = "查询文档列表", description = "获取文档列表，支持按分类、文件名筛选和分页")
    //@RequiresPermissions("ai:document:list")
    @GetMapping("/list")
    public TableDataInfo list(
            @Parameter(description = "文档分类ID") @RequestParam String categoryId,
            @Parameter(description = "文件名关键字") @RequestParam(required = false) String fileName,
            @Parameter(description = "分页标记") @RequestParam(required = false) String nextToken,
            @Parameter(description = "每页最大数量") @RequestParam(required = false) Integer maxResults) {
        return documentService.selectDocumentList(categoryId, fileName, nextToken, maxResults);
    }

    /**
     * 添加文档
     */
    @Operation(summary = "添加文档", description = "添加一个新文档")
    //@RequiresPermissions("ai:document:add")
    @Log(title = "文档管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Parameter(description = "添加文档参数", required = true) @RequestBody AddFileDTO addFileDTO) {
        return success(documentService.addDocument(addFileDTO));
    }

    /**
     * 申请上传租约(接口仅用于测试)
     */
    @Operation(summary = "申请上传租约", description = "申请文件上传租约，用于后续上传权限校验")
    //@RequiresPermissions("ai:document:lease")
    @GetMapping("/apply-lease")
    public AjaxResult applyLease(
            @Parameter(description = "文件名", required = true) @RequestParam String fileName,
            @Parameter(description = "文件MD5值", required = true) @RequestParam String md5,
            @Parameter(description = "文件大小（字节）", required = true) @RequestParam String sizeInBytes) {
        return success(documentService.applyUploadLease(fileName, md5, sizeInBytes));
    }

    /**
     * 删除文档
     */
    @Operation(summary = "删除文档", description = "从知识库中删除指定的文档")
    //@RequiresPermissions("ai:document:remove")
    @Log(title = "文档管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fileId}")
    public AjaxResult remove(@Parameter(description = "文档ID", required = true) @PathVariable String fileId) {
        return toAjax(documentService.deleteDocument(fileId));
    }

    /**
     * 批量删除文档
     */
    @Operation(summary = "批量删除文档", description = "批量删除文档")
    //@RequiresPermissions("ai:document:remove")
    @Log(title = "文档管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch")
    public AjaxResult removeBatch(@Parameter(description = "文档ID数组", required = true) @RequestBody List<String> fileIds) {
        return toAjax(documentService.deleteDocuments(fileIds));
    }

    /**
     * 查询文档状态
     */
    @Operation(summary = "查询文档状态", description = "查询文档当前状态")
    //@RequiresPermissions("ai:document:query")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@Parameter(description = "文档ID", required = true) @PathVariable String fileId) {
        return success(documentService.selectDocumentById(fileId));
    }

    /**
     * 更新文档标签
     */
    @Operation(summary = "更新文档标签", description = "更新文档的标签信息")
    //@RequiresPermissions("ai:document:update-tag")
    @Log(title = "文档管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{fileId}/tags")
    public AjaxResult updateTags(@Parameter(description = "文档ID", required = true) @PathVariable String fileId,
                                 @Parameter(description = "新的标签数组", required = true) @RequestBody List<String> tags) {
        return toAjax(documentService.updateDocumentTags(fileId, tags));
    }

    /**
     * 从授权OSS导入文件
     */
    @Operation(summary = "从授权OSS导入文件", description = "从已授权的OSS批量导入文件")
    //@RequiresPermissions("ai:document:import-oss")
    @Log(title = "文档管理", businessType = BusinessType.INSERT)
    @PostMapping("/import-from-oss")
    public AjaxResult importFromOss(
            @Parameter(description = "目标分类ID", required = true) @RequestParam String categoryId,
            @Parameter(description = "OSS区域ID", required = true) @RequestParam String ossRegionId,
            @Parameter(description = "OSS存储桶名称", required = true) @RequestParam String ossBucketName,
            @Parameter(description = "文件列表", required = true) @RequestBody List<Map<String, String>> fileDetails,
            @Parameter(description = "文件标签（可选）") @RequestParam(required = false) List<String> tags) {
        boolean result = documentService.addFilesFromOss(categoryId, ossRegionId, ossBucketName, fileDetails, tags);
        return result ? success("导入成功") : error("导入失败");
    }
}